package ru.spbau.design.snmp.android.viewer.searcher;

import ru.spbau.design.snmp.android.viewer.model.IPAddress;
import ru.spbau.design.snmp.android.viewer.model.NetInterface;
import ru.spbau.design.snmp.android.viewer.model.NetNode;
import ru.spbau.design.snmp.android.viewer.model.Network;
import ru.spbau.design.snmp.android.viewer.model.NetworkSnapshot;
import ru.spbau.design.snmp.android.viewer.model.Router;
import ru.spbau.design.snmp.android.viewer.model.SubNet;

public final class SearcherSimple implements ISearcher {

	@Override
	public SearchResult search(String query, NetworkSnapshot snapshot) {
		SearchResult result = new SearchResult();
		
		for (Network network : snapshot.getNetworks()) {

			if (tryString(query, network.getId())) {
				result.addNetwork(network);
			}

			for (SubNet subNet : network.getSubNets()) {
				
				boolean subNetAdded = false;
				if (tryString(query, subNet.getId())
					&& !subNetAdded) {
					result.addSubNet(subNet);
					subNetAdded = true;
				}
				
				if (tryIP(query, subNet.getNetMask())
					&& !subNetAdded) {
					result.addSubNet(subNet);
					subNetAdded = true;
				}
				
				for (NetNode netNode : subNet.getNodes()) {
					if (tryIP(query, netNode.getAddress())) {
						result.addNetNode(netNode);
					}
				}
			}

			for (Router router : network.getRouters()) {
				boolean routerAdded = false;
				if (tryStringNonStrict(query, router.getDescription())
					&& !routerAdded) {
					result.addRouter(router);
					routerAdded = true;
				}
				for (NetInterface netInterface : router.getInterfaces()) {
					
					if (tryIP(query, netInterface.getAddress())
						&& !routerAdded) {
						result.addRouter(router);
						routerAdded = true;
					}
					
					if (tryMask(query, netInterface.getAddress())
						&& !routerAdded) {
						result.addRouter(router);
						routerAdded = true;
					}
					
					if (tryStringNonStrict(query, netInterface.getName())
						&& !routerAdded) {
						result.addRouter(router);
						routerAdded = true;
					}
				}
			}
		}
		
		return result;
	}

	private boolean tryString(String query, String str) {
		return query.equals(str);
	}

	private boolean tryStringNonStrict(String query, String str) {
		return str.contains(query);
	}

	private boolean tryIP(String query, IPAddress ip) {
		return query.equals(ip.getAddressStr());
	}

	private boolean tryMask(String query, IPAddress ip) {
		return query.equals(ip.getMaskStr());
	}
}
